#include "AlarmRuleDialog.h"
#include "core/ChannelManager.h"
#include "core/Channel.h"
#include "core/UniversalDataModel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QGroupBox>
#include <QLabel>
#include <QMessageBox>
#include <QUuid>
#include <QDebug>

namespace ModbusPlexLink {

AlarmRuleDialog::AlarmRuleDialog(ChannelManager* channelManager,
                                 const AlarmRule* rule,
                                 QWidget *parent)
    : QDialog(parent)
    , m_channelManager(channelManager)
    , m_isEdit(rule != nullptr)
    , m_originalId(rule ? rule->id : QString())
    , m_nameEdit(nullptr)
    , m_enabledCheck(nullptr)
    , m_priorityCombo(nullptr)
    , m_typeCombo(nullptr)
    , m_channelCombo(nullptr)
    , m_tagCombo(nullptr)
    , m_highLimitSpin(nullptr)
    , m_lowLimitSpin(nullptr)
    , m_highHighLimitSpin(nullptr)
    , m_lowLowLimitSpin(nullptr)
    , m_delaySpin(nullptr)
    , m_deadbandSpin(nullptr)
    , m_messageEdit(nullptr)
    , m_okBtn(nullptr)
    , m_cancelBtn(nullptr)
{
    setWindowTitle(m_isEdit ? tr("编辑报警规则") : tr("新建报警规则"));
    resize(600, 700);
    setModal(true);

    setupUi();
    loadChannelsAndTags();

    if (rule) {
        loadRule(*rule);
    } else {
        // 默认设置
        m_enabledCheck->setChecked(true);
        m_priorityCombo->setCurrentIndex(1);  // Medium
        m_typeCombo->setCurrentIndex(0);      // HighLimit
        m_delaySpin->setValue(5);
        m_deadbandSpin->setValue(0.0);
        m_messageEdit->setPlainText(tr("${tag} 触发 ${type} 报警，当前值: ${value}"));
    }

    updateLimitFields();
}

AlarmRuleDialog::~AlarmRuleDialog() {
}

void AlarmRuleDialog::setupUi() {
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(15, 15, 15, 15);
    mainLayout->setSpacing(15);

    // === 基本信息组 ===
    QGroupBox* basicGroup = new QGroupBox(tr("基本信息"), this);
    QFormLayout* basicLayout = new QFormLayout(basicGroup);
    basicLayout->setSpacing(10);

    m_nameEdit = new QLineEdit(this);
    m_nameEdit->setPlaceholderText(tr("输入规则名称，例如：温度高限报警"));
    basicLayout->addRow(tr("规则名称:"), m_nameEdit);

    m_enabledCheck = new QCheckBox(tr("启用此规则"), this);
    basicLayout->addRow(tr("状态:"), m_enabledCheck);

    m_priorityCombo = new QComboBox(this);
    m_priorityCombo->addItems({tr("低"), tr("中"), tr("高"), tr("紧急")});
    basicLayout->addRow(tr("优先级:"), m_priorityCombo);

    m_typeCombo = new QComboBox(this);
    m_typeCombo->addItems({
        tr("高限报警"),
        tr("低限报警"),
        tr("高高限报警"),
        tr("低低限报警"),
        tr("值变化报警"),
        tr("数据质量报警"),
        tr("连接丢失报警")
    });
    connect(m_typeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AlarmRuleDialog::onAlarmTypeChanged);
    basicLayout->addRow(tr("报警类型:"), m_typeCombo);

    mainLayout->addWidget(basicGroup);

    // === 数据源组 ===
    QGroupBox* sourceGroup = new QGroupBox(tr("数据源"), this);
    QFormLayout* sourceLayout = new QFormLayout(sourceGroup);
    sourceLayout->setSpacing(10);

    m_channelCombo = new QComboBox(this);
    connect(m_channelCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AlarmRuleDialog::onChannelChanged);
    sourceLayout->addRow(tr("通道:"), m_channelCombo);

    m_tagCombo = new QComboBox(this);
    m_tagCombo->setEditable(true);
    sourceLayout->addRow(tr("标签:"), m_tagCombo);

    mainLayout->addWidget(sourceGroup);

    // === 条件配置组 ===
    QGroupBox* conditionGroup = new QGroupBox(tr("报警条件"), this);
    QFormLayout* conditionLayout = new QFormLayout(conditionGroup);
    conditionLayout->setSpacing(10);

    m_highLimitSpin = new QDoubleSpinBox(this);
    m_highLimitSpin->setRange(-999999.0, 999999.0);
    m_highLimitSpin->setDecimals(2);
    conditionLayout->addRow(tr("高限值:"), m_highLimitSpin);

    m_lowLimitSpin = new QDoubleSpinBox(this);
    m_lowLimitSpin->setRange(-999999.0, 999999.0);
    m_lowLimitSpin->setDecimals(2);
    conditionLayout->addRow(tr("低限值:"), m_lowLimitSpin);

    m_highHighLimitSpin = new QDoubleSpinBox(this);
    m_highHighLimitSpin->setRange(-999999.0, 999999.0);
    m_highHighLimitSpin->setDecimals(2);
    conditionLayout->addRow(tr("高高限值:"), m_highHighLimitSpin);

    m_lowLowLimitSpin = new QDoubleSpinBox(this);
    m_lowLowLimitSpin->setRange(-999999.0, 999999.0);
    m_lowLowLimitSpin->setDecimals(2);
    conditionLayout->addRow(tr("低低限值:"), m_lowLowLimitSpin);

    m_delaySpin = new QSpinBox(this);
    m_delaySpin->setRange(0, 3600);
    m_delaySpin->setSuffix(tr(" 秒"));
    m_delaySpin->setToolTip(tr("报警延迟时间，条件持续满足此时长后才触发报警"));
    conditionLayout->addRow(tr("延迟时间:"), m_delaySpin);

    m_deadbandSpin = new QDoubleSpinBox(this);
    m_deadbandSpin->setRange(0.0, 999999.0);
    m_deadbandSpin->setDecimals(2);
    m_deadbandSpin->setToolTip(tr("死区带宽，避免报警频繁触发"));
    conditionLayout->addRow(tr("死区带宽:"), m_deadbandSpin);

    mainLayout->addWidget(conditionGroup);

    // === 消息模板组 ===
    QGroupBox* messageGroup = new QGroupBox(tr("消息模板"), this);
    QVBoxLayout* messageLayout = new QVBoxLayout(messageGroup);

    QLabel* hintLabel = new QLabel(tr("可用变量: ${channel}, ${tag}, ${type}, ${value}, ${priority}"), this);
    hintLabel->setStyleSheet("color: gray; font-size: 10pt;");
    messageLayout->addWidget(hintLabel);

    m_messageEdit = new QTextEdit(this);
    m_messageEdit->setMaximumHeight(80);
    messageLayout->addWidget(m_messageEdit);

    mainLayout->addWidget(messageGroup);

    // === 按钮组 ===
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();

    m_okBtn = new QPushButton(tr("确定"), this);
    m_okBtn->setMinimumWidth(100);
    connect(m_okBtn, &QPushButton::clicked, this, &AlarmRuleDialog::onOkClicked);
    buttonLayout->addWidget(m_okBtn);

    m_cancelBtn = new QPushButton(tr("取消"), this);
    m_cancelBtn->setMinimumWidth(100);
    connect(m_cancelBtn, &QPushButton::clicked, this, &AlarmRuleDialog::onCancelClicked);
    buttonLayout->addWidget(m_cancelBtn);

    mainLayout->addLayout(buttonLayout);
}

void AlarmRuleDialog::loadChannelsAndTags() {
    if (!m_channelManager) {
        return;
    }

    // 加载通道列表
    m_channelCombo->clear();
    QStringList channelNames = m_channelManager->getChannelNames();
    for (const QString& channelName : channelNames) {
        m_channelCombo->addItem(channelName, channelName);
    }

    // 如果有通道，加载第一个通道的标签
    if (m_channelCombo->count() > 0) {
        onChannelChanged(0);
    }
}

void AlarmRuleDialog::onChannelChanged(int index) {
    m_tagCombo->clear();

    if (index < 0 || !m_channelManager) {
        return;
    }

    QString channelName = m_channelCombo->itemData(index).toString();
    Channel* channel = m_channelManager->getChannel(channelName);

    if (!channel) {
        return;
    }

    // 获取该通道的 UniversalDataModel
    UniversalDataModel* udm = channel->getDataModel();
    if (!udm) {
        return;
    }

    // 加载该通道的所有标签
    QStringList tagNames = udm->getAllTags();
    for (const QString& tagName : tagNames) {
        m_tagCombo->addItem(tagName);
    }
}

void AlarmRuleDialog::onAlarmTypeChanged(int index) {
    Q_UNUSED(index);
    updateLimitFields();
}

void AlarmRuleDialog::updateLimitFields() {
    int typeIndex = m_typeCombo->currentIndex();

    // 禁用所有限值字段
    m_highLimitSpin->setEnabled(false);
    m_lowLimitSpin->setEnabled(false);
    m_highHighLimitSpin->setEnabled(false);
    m_lowLowLimitSpin->setEnabled(false);

    // 根据类型启用相应字段
    switch (typeIndex) {
        case 0:  // HighLimit
            m_highLimitSpin->setEnabled(true);
            break;
        case 1:  // LowLimit
            m_lowLimitSpin->setEnabled(true);
            break;
        case 2:  // HighHighLimit
            m_highHighLimitSpin->setEnabled(true);
            break;
        case 3:  // LowLowLimit
            m_lowLowLimitSpin->setEnabled(true);
            break;
        default:
            // ValueChange, DataQuality, ConnectionLost 不需要限值
            break;
    }
}

void AlarmRuleDialog::loadRule(const AlarmRule& rule) {
    m_nameEdit->setText(rule.name);
    m_enabledCheck->setChecked(rule.enabled);
    m_priorityCombo->setCurrentIndex(static_cast<int>(rule.priority));
    m_typeCombo->setCurrentIndex(static_cast<int>(rule.type));

    // 设置通道
    for (int i = 0; i < m_channelCombo->count(); ++i) {
        if (m_channelCombo->itemText(i) == rule.channelName) {
            m_channelCombo->setCurrentIndex(i);
            break;
        }
    }

    // 设置标签
    m_tagCombo->setCurrentText(rule.tagName);

    // 设置限值
    m_highLimitSpin->setValue(rule.highLimit);
    m_lowLimitSpin->setValue(rule.lowLimit);
    m_highHighLimitSpin->setValue(rule.highHighLimit);
    m_lowLowLimitSpin->setValue(rule.lowLowLimit);

    m_delaySpin->setValue(rule.delaySeconds);
    m_deadbandSpin->setValue(rule.deadband);
    m_messageEdit->setPlainText(rule.message);
}

bool AlarmRuleDialog::validateInput() {
    // 检查规则名称
    if (m_nameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, tr("验证失败"), tr("请输入规则名称"));
        m_nameEdit->setFocus();
        return false;
    }

    // 检查通道
    if (m_channelCombo->currentIndex() < 0) {
        QMessageBox::warning(this, tr("验证失败"), tr("请选择通道"));
        m_channelCombo->setFocus();
        return false;
    }

    // 检查标签
    if (m_tagCombo->currentText().trimmed().isEmpty()) {
        QMessageBox::warning(this, tr("验证失败"), tr("请选择或输入标签名称"));
        m_tagCombo->setFocus();
        return false;
    }

    // 检查限值设置（根据类型）
    int typeIndex = m_typeCombo->currentIndex();
    if (typeIndex == 0 && !m_highLimitSpin->isEnabled()) {
        QMessageBox::warning(this, tr("验证失败"), tr("请设置高限值"));
        return false;
    }
    if (typeIndex == 1 && !m_lowLimitSpin->isEnabled()) {
        QMessageBox::warning(this, tr("验证失败"), tr("请设置低限值"));
        return false;
    }

    // 检查消息模板
    if (m_messageEdit->toPlainText().trimmed().isEmpty()) {
        QMessageBox::warning(this, tr("验证失败"), tr("请输入消息模板"));
        m_messageEdit->setFocus();
        return false;
    }

    return true;
}

AlarmRule AlarmRuleDialog::getRule() const {
    AlarmRule rule;

    // 如果是编辑模式，保留原始ID；否则生成新ID
    rule.id = m_isEdit ? m_originalId : QUuid::createUuid().toString(QUuid::WithoutBraces);

    rule.name = m_nameEdit->text().trimmed();
    rule.enabled = m_enabledCheck->isChecked();
    rule.priority = static_cast<AlarmPriority>(m_priorityCombo->currentIndex());
    rule.type = static_cast<AlarmType>(m_typeCombo->currentIndex());

    // 获取通道名称（直接使用显示的文本）
    if (m_channelCombo->currentIndex() >= 0) {
        rule.channelName = m_channelCombo->currentText();
    }

    rule.tagName = m_tagCombo->currentText().trimmed();

    rule.highLimit = m_highLimitSpin->value();
    rule.lowLimit = m_lowLimitSpin->value();
    rule.highHighLimit = m_highHighLimitSpin->value();
    rule.lowLowLimit = m_lowLowLimitSpin->value();

    rule.delaySeconds = m_delaySpin->value();
    rule.deadband = m_deadbandSpin->value();
    rule.message = m_messageEdit->toPlainText();

    return rule;
}

void AlarmRuleDialog::onOkClicked() {
    if (validateInput()) {
        accept();
    }
}

void AlarmRuleDialog::onCancelClicked() {
    reject();
}

} // namespace ModbusPlexLink
